import { addLog } from './utils'
const path = require('path')
const dayjs = require('dayjs')
const fs = require('fs')
const { Options } = require('selenium-webdriver/chrome')
const { Builder, By, Browser } = require('selenium-webdriver')

export async function getOrders(orders) {
  console.log('%c [ orders ]-9', 'font-size:13px; background:#333333; color:#f3f3f3;', orders)
  const options = new Options()

  options.debuggerAddress('127.0.0.1:9223')

  // 第一页
  let driver = await new Builder().forBrowser(Browser.CHROME).setChromeOptions(options).build()

  // 加载登录页

  // await driver.get('http://www.teste.com/')
  await driver.get('https://envios.adminml.com/cbt/scheduling/is-listing')
  let rows = await driver.findElements(By.className('andes-table__row linked'))
  let preferential = await driver.findElements(By.className('andes-table__row preferential'))
  let onway = await driver.findElements(By.className('andes-table__row on_way'))
  rows = rows.concat(preferential)
  // 插入在途
  rows = rows.concat(onway)

  if (rows.length == 0) {
    console.log('no orders')
    return
  }

  let ids = []

  for (let i = 0; i < rows.length; i++) {
    let row = rows[i]

    // 获取每个可点击项的id
    let column = await row.findElements(
      By.className('andes-table__column andes-table__column--left')
    )

    let id = await column[1].getText()
    console.log('id', id)
    let needRun = false
    orders.map((order) => {
      console.log('order', order)
      if (order.id.indexOf(id) != -1) {
        console.log('has same id')
        // ids = `${ids},${id}`
        ids.push(id)
        needRun = true
      }
    })

    if (needRun) {
      console.log('running ')
      let checkInput = await column[0].findElement(By.className('andes-checkbox__input'))
      let isSelect = await checkInput.isSelected()
      console.log('checkInput isSelect', isSelect)

      if (!isSelect) {
        await checkInput.click()

        await driver.sleep(1000)

        // 勾选完之后判断是否有橙色按钮需要点击 如果有就点击
        let orangeBtn = await driver.findElements(
          By.className(
            'andes-button andes-message__primary-button-inline andes-message__primary-button--warning andes-button--medium andes-button--loud'
          )
        )
        console.log('orangeBtn.length', orangeBtn.length)
        if (orangeBtn.length > 0) {
          orangeBtn.map(async (btn) => {
            console.log('btn', await btn.getText())
            if ((await btn.getText()) == 'Confirmar') {
              console.log('Need click')
              await btn.click()

              await driver.sleep(1000)
              let modalScroll = await driver.findElement(By.className('andes-modal__scroll'))
              let btn1 = await modalScroll.findElement(
                By.className('andes-button andes-button--large andes-button--loud')
              )
              await btn1.click()
            }
          })
        }
      }
    }
  }

  if (ids.length == 0) {
    addLog({
      type: 'error',
      msg: '没有需要执行的任务',
      time: dayjs().format('YYYY-MM-DD HH:mm:ss')
    })
    return
  }

  // 滚动到顶部
  await driver.executeScript('window.scrollTo(0,0)')

  // 找到提交按钮
  let submitBtn = await driver.findElement(By.id('appointment_button'))

  let submitBtnText = await submitBtn.getText()
  console.log('submitBtn:', submitBtnText)

  if (submitBtnText.indexOf('Agendar') != -1) {
    console.log(`run order ${submitBtnText}`)
    await submitBtn.click()
  } else {
    // console.log('没有找到执行任务按钮')
    addLog({
      type: 'error',
      msg: '没有找到执行任务按钮',
      time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      data: orders
    })
    return
  }

  // 第二页
  // await driver.get('http://www.teste.com/submit.html')
  await driver.sleep(2000)

  await driver.get('https://envios.adminml.com/cbt/scheduling/appointment?iss=' + ids.join(','))

  await driver.sleep(1000)
  // 输入框focus
  let timeInput = await driver.findElement(By.className('andes-form-control__field'))
  await timeInput.click()

  await driver.sleep(1000)
  await driver.executeScript('window.scrollTo(1800,0)')

  let days = await driver.findElements(By.className('day'))

  let dayTxt = dayjs().endOf('month').format('DD')
  // 可以被选择的日期
  let canSelectDays = []
  let isOver = false

  for (let i = 7; i < days.length; i++) {
    if (!isOver) {
      let itemText = await days[i].getText()
      if (itemText == dayTxt) {
        isOver = true
      }

      let classText = await days[i].getAttribute('class')

      if (classText.indexOf('day--disabled') == -1) {
        canSelectDays.push(days[i])
      }
    }
  }

  let runOver = false

  // 循环点击时间 查看小时是否可以下单
  for (let idx = 0; idx < canSelectDays.length; idx++) {
    let item = canSelectDays[idx]
    if (runOver) {
      return
    }

    let day = await item.getText()
    console.log('%c [ day ]-113', 'font-size:13px; background:#333333; color:#f3f3f3;', day)
    await item.click()
    // 每天点击后等待2S
    await driver.sleep(500)

    let hours = await driver.findElements(By.className('hour'))
    console.log('%c [ hours length ]-172', hours.length)
    let confirm = await driver.findElement(By.id(':Rkt4pu:'))

    await driver.sleep(1000)

    for (let index = 0; index < hours.length; index++) {
      console.log('runOver', runOver)

      if (!runOver) {
        let hour = hours[index]
        let classText = await hour.getAttribute('class')

        if (classText.indexOf('hour--disabled') == -1) {
          // 可点击
          let hourTxt = await hour.getText()
          console.log(
            '%c [ hourTxt ]-124',
            'font-size:13px; background:#333333; color:#f3f3f3;',
            hourTxt
          )
          // 拼凑时间
          let time = dayjs().date(parseInt(day)).hour(parseInt(hourTxt)).valueOf()
          console.log('Click Time', dayjs(time).format('YYYY-MM-DD HH:mm:ss'))
          // 将time与传入的数据对比
          for (let i = 0; i < orders.length; i++) {
            if (!runOver) {
              let order = orders[i]
              if (time >= order.timeRange[0] && time <= order.timeRange[1]) {
                console.log('Start time:', dayjs(order.timeRange[0]).format('YYYY-MM-DD HH:mm:ss'))
                console.log('End time:', dayjs(order.timeRange[1]).format('YYYY-MM-DD HH:mm:ss'))

                await driver.sleep(1000)
                // 下单
                await hour.click()
                await driver.sleep(1000)

                await confirm.click()
                runOver = true

                break
              }
            }
          }
        }
      }
    }
  }

  // 判断上一页是否已执行
  if (!runOver) {
    // 加载下一页
    await loadNextPage(driver, orders)
  }

  // 执行下单操作
  let submitContent = await driver.findElement(By.className('btn-cont'))
  let btn = await submitContent.findElement(
    By.className('andes-button andes-button--large andes-button--loud')
  )

  console.log('btn txt:', await btn.getText())
  // await btn.click()
}

async function loadNextPage(driver, orders) {
  let nextBtn = await driver.findElement(
    By.className(
      'focus-ui-datepicker__content__month-selector focus-ui-datepicker__content__month-selector--next'
    )
  )
  await nextBtn.click()

  let month = dayjs().month() + 1

  // 获取下一页的day按钮
  let days = await driver.findElements(By.className('day'))
  // 可以被选择的日期
  let canSelectDays = []
  let isOver = false

  let startCountDay = false

  let dayTxt = dayjs().month(month).endOf('month').format('DD')

  for (let i = 7; i < days.length; i++) {
    if (!isOver) {
      let itemText = await days[i].getText()
      let number = parseInt(itemText)

      if (number == 1 || startCountDay) {
        console.log('number:', number)

        startCountDay = true

        if (itemText == dayTxt) {
          isOver = true
        }

        let classText = await days[i].getAttribute('class')

        if (classText.indexOf('day--disabled') == -1) {
          canSelectDays.push(days[i])
        }
      }
    }
  }

  console.log('canSelectDays.length', canSelectDays.length)

  let runOver = false

  // 循环点击时间 查看小时是否可以下单
  for (let idx = 0; idx < canSelectDays.length; idx++) {
    let item = canSelectDays[idx]
    if (runOver) {
      return
    }

    let day = await item.getText()
    console.log('%c [ day ]-113', 'font-size:13px; background:#333333; color:#f3f3f3;', day)
    await item.click()

    let hours = await driver.findElements(By.className('hour'))
    let confirm = await driver.findElement(By.id(':Rkt4pu:'))

    await driver.sleep(1000)

    for (let index = 0; index < hours.length; index++) {
      if (!runOver) {
        let hour = hours[index]
        let classText = await hour.getAttribute('class')
        if (classText.indexOf('hour--disabled') == -1) {
          // 可点击
          let hourTxt = await hour.getText()
          console.log(
            '%c [ hourTxt ]-124',
            'font-size:13px; background:#333333; color:#f3f3f3;',
            hourTxt
          )
          // 拼凑时间
          let time = dayjs().month(month).date(parseInt(day)).hour(parseInt(hourTxt)).valueOf()
          console.log(dayjs(time).format('YYYY-MM-DD HH:mm:ss'))
          console.log('orders', orders)

          // 将time与传入的数据对比
          for (let i = 0; i < orders.length; i++) {
            if (!runOver) {
              let order = orders[i]
              if (time >= order.timeRange[0] && time <= order.timeRange[1]) {
                await driver.sleep(1000)
                // 下单
                await hour.click()
                await driver.sleep(1000)

                await confirm.click()
                runOver = true

                break
              }
            }
          }
        }
      }
    }
  }
}

export async function saveForm(list) {
  // 保存表单
  let content = JSON.stringify(list)
  // const savePath = path.join(__dirname + '/resources/save/', 'save.json')
  const savePath = 'C:\\appData\\save\\save.json'
  fs.writeFile(savePath, content, { flag: 'w' }, (err) => {
    if (err) {
      console.log('err', err)
    }
  })
}
/**
 * 从文件中获取数据
 */
export function initData() {
  return fs.readFileSync('C:\\appData\\save\\save.json', 'utf8')
}
